export default function useExcelPaste(effect, maximum = 100000) {
  if (typeof effect !== 'function') {
    throw Error('parameter `effect` is invalid.')
  }

  const handler = (e: ClipboardEvent) => {
    // @ts-ignore
    const clipboardData = window.clipboardData || e.clipboardData

    if (!clipboardData || !clipboardData.items) {
      console.warn('Can not get available data from clipboard.')
      return
    }

    let table = []
    let excelContent = (clipboardData.getData('text') || clipboardData.getData('Text') || '').trim()
    if (excelContent) {
      let lines = excelContent.split('\n')
      if (lines.length > maximum) {
        console.warn(`Since the amount of rows is more over than maximum ${maximum}, data truncation has happened.`)
      }
      lines = lines.slice(0, maximum)
      table = lines.map(line => line.replace(/\"/g, '').trim())
        .filter(line => !!line)
        .map(line => line.split('\t').map(col => col.trim()))

      effect(table)
    }
  }

  let ctner = null
  const bind = (container: HTMLElement) => {
    ctner = container
    ctner.addEventListener('paste', handler)
  }
  const unbind = () => {
    ctner.removeEventListener('paste', handler)
  }

  return [
    bind,
    unbind,
  ]
}